<template>
  <div class="v-ckeditor">
    <ckeditor
      :editor="editor"
      :disabled="disabled"
      :value="editorData"
      :config="editorConfig"
      @input="changeEditorData"
      @ready="onReady"
    />
  </div>
</template>

<script>
import CKEditor from '@ckeditor/ckeditor5-vue2';
import DocumentEditor from '@ckeditor/ckeditor5-build-decoupled-document';
import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn.js';
import axios from 'axios';

export default {
  components: {
    ckeditor: CKEditor.component,
  },

  props: {
    value: {
      type: String,
      default: '',
    },
    url: {
      type: String,
      default: `${process.env.VUE_APP_URL}/home/file/upload`,
    },
    tenantId: {
      type: String,
      default: 'CustApp',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      editor: DocumentEditor,
      editorData: '',
      editorConfig: {
        language: 'zh-cn',
        toolbar: [
          'heading',
          '|',
          'fontfamily',
          'fontsize',
          'fontColor',
          'fontBackgroundColor',
          '|',
          'bold',
          'italic',
          'underline',
          'strikethrough',
          '|',
          'alignment',
          '|',
          'numberedList',
          'bulletedList',
          '|',
          'outdent',
          'indent',
          '|',
          'link',
          'blockquote',
          'uploadImage',
          'insertTable', // 'uploadImage',
          '|', // 'mediaEmbed',
          'undo',
          'redo',
        ],
        heading: {
          options: [
            {
              model: 'paragraph',
              title: 'Paragraph',
              class: 'ck-heading_paragraph',
            },
            {
              model: 'heading1',
              view: 'h1',
              title: 'Heading 1',
              class: 'ck-heading_heading1',
            },
            {
              model: 'heading2',
              view: 'h2',
              title: 'Heading 2',
              class: 'ck-heading_heading2',
            },
            {
              model: 'heading3',
              view: 'h3',
              title: 'Heading 3',
              class: 'ck-heading_heading3',
            },
            {
              model: 'heading4',
              view: 'h4',
              title: 'Heading 4',
              class: 'ck-heading_heading4',
            },
            {
              model: 'heading5',
              view: 'h5',
              title: 'Heading 5',
              class: 'ck-heading_heading5',
            },
            {
              model: 'heading6',
              view: 'h6',
              title: 'Heading 6',
              class: 'ck-heading_heading6',
            },
          ],
        },
        fontColor: {
          columns: 6, // Display 6 columns in the color grid.
          documentColors: 12, // And 12 document colors (2 rows of them).
        },
        fontBackgroundColor: {
          documentColors: 0, // Remove the "Document colors" section.
        },
        fontFamily: {
          options: [
            'default',
            'Georgia, serif',
            'Trebuchet MS, Helvetica, sans-serif',
            'Verdana, Geneva, sans-serif',
            '微软雅黑',
            '宋体',
            '仿宋_GB2312',
          ],
          supportAllValues: true,
        },
        fontSize: {
          options: [8, 9, 10, 11, 12, 'default', 14, 16, 18, 20, 21, 24, 26, 29],
        },
        indentText: {
          options: {
            indentLength: 10,
            indentMeasure: 'px',
          },
        },
      },
    };
  },

  watch: {
    value: {
      handler(value) {
        if (this.editorData !== value) {
          this.editorData = value || '';
        }
      },
      immediate: true,
    },
  },

  methods: {
    onReady(editor) {
      editor.ui
        .getEditableElement()
        .parentElement.insertBefore(editor.ui.view.toolbar.element, editor.ui.getEditableElement());

      editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
        return {
          upload: () => {
            // eslint-disable-next-line no-async-promise-executor
            return new Promise(async (resolve, reject) => {
              const formdata = new FormData();
              // formdata.append('tenantId', this.tenantId);
              // formdata.append('fileSelect', await loader.file);
              formdata.append('file', await loader.file);
              axios({
                url: this.url,
                method: 'post',
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                },
                data: formdata,
              })
                .then((res) => {
                  console.log(res);
                  if (res.status === 200 && res.data && res.data.code === 0) {
                    console.log(
                      `${process.env.VUE_APP_URL}/assets/files/${res.data.fileInfo.filePath}`
                    );
                    resolve({
                      default: res.data.fileInfo.filePath,
                      // default: `${process.env.VUE_APP_URL}/src/assets/files/${res.data.fileInfo.filePath}`,
                    });
                  } else {
                    reject(res.statusText || res.data);
                  }
                })
                .catch((error) => {
                  reject(error.message);
                });
            });
          },
        };
      };
    },

    changeEditorData(value) {
      this.editorData = value;
      this.$emit('input', value);
      this.$emit('change', value);
    },
  },
};
</script>

<style lang="scss" scoped>
.v-ckeditor {
  overflow: hidden;
  ::v-deep .ck.ck-editor__editable_inline {
    max-height: 400px;
    min-height: 100px;
    border: 1px solid #b3b3b3;
    border-top-width: 0px;
    margin-top: -1px;
    line-height: 1.5;
  }
}
</style>
